package com.mfcxy.serviceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mfcxy.entity.Permissions;
import com.mfcxy.entity.RolePermission;
import com.mfcxy.mapper.IPermissionsMapper;
import com.mfcxy.mapper.IRolePermissionMapper;
import com.mfcxy.service.IRolePermissionService;

@Service
public class RolePermissionService extends BaseService implements IRolePermissionService {

	@Autowired
	private IRolePermissionMapper rp;
	
	@Autowired
	private IPermissionsMapper permissionsMapper;

	/**
	 * 根据角色id查询对应权限和所有权限
	 * 
	 * @param rid
	 * @return
	 */
	@Override
	public List<Permissions> selectRidAndPid(int rid) {
		// TODO Auto-generated method stub
		List<RolePermission> rplist = rp.selectList(rid);
		List<Permissions> plist = permissionsMapper.selectListAll();
		for (Permissions permissions : plist) { //所有的权限
			for (RolePermission rolePermission : rplist) {
				// 如果用户拥有改权限
				if (permissions.getId() == rolePermission.getPermissionid()) {
					permissions.setChecked(true);
				} 
			}
		}
		return plist;
	}

	/**
	 * 更新角色权限
	 * 
	 * @param pids 角色权限id 集合
	 * @param rid  角色权限
	 */
	@Override
	public void updateRidAndPid(String pids, int rid) {
		// TODO Auto-generated method stub
		// 清空原有权限
		rp.deleteRidAndPid(rid);
		// 如果有提交任何新权限数据
		if (!pids.equals("")) {
			// 字符串转数组
			String[] sArray = pids.split(",");
			ArrayList<RolePermission> rps = new ArrayList<>();
			// 创建RolePermission 对象
			for (String string : sArray) {
				RolePermission rp = new RolePermission();
				rp.setId(getTools().getUUID32());
				rp.setPermissionid(Integer.parseInt(string));
				rp.setRoleid(rid);
				rps.add(rp);
			}
			rp.insertRidAndPid(rps);
		}
	}

}
